<!--
 * @Description:
 * @Author: dh
 * @Date: 2021-09-27 16:22:40
 * @LastEditors: dh
 * @LastEditTime: 2025-09-15 13:27:01
-->
<!DOCTYPE html>

<body>
  <div id="box">0</div>
  <script>
    const box = document.querySelector("#box");

    // 创建worker
    function createWorker(f) {
      // 包装为立即执行函数
      const workerContent = "(" + f.toString() + ")()"
      const blob = new Blob([workerContent]);
      const url = window.URL.createObjectURL(blob);
      const worker = new Worker(url);
      return worker;
    }

    var myWorker = createWorker(function (e) {
      addEventListener('message', function (e) {
        console.log("%cworker-收到消息：" + e.data, "color:blue");
      }, false);

      let num = 0;
      setInterval(function () {
        num++;
        self.postMessage(num);
      }, 1000);
    });


    myWorker.onmessage = function (e) {
      console.log(e.data);
      box.textContent = e.data;
    };

    myWorker.postMessage("init");
  </script>
</body>

</html>